//用户相关状态管理

import {createSlice} from "@reduxjs/toolkit";
import {getToken, http, removeToken, setToken as _setToken} from "@/utils";
import {getUserInfoAPI, loginAPI} from "@/apis/user";

const user = createSlice({
    name:"user",
    initialState:{
        token: getToken()||'',
        userInfo:{}
    },
    reducers:{
        setToken(state,action){
            state.token = action.payload
            _setToken(action.payload)
        },
        setUserInfo(state,action){
            state.userInfo = action.payload
        },
        clearUserInfo(state){
            state.token=''
            state.userInfo = []
            removeToken()
        }
    }
})
//异步请求获取Token
const fetchToken = (tokenForm)=>{
    return async (dispatch)=>{
        const res = await loginAPI(tokenForm)
        dispatch(setToken(res.data.token))
    }
}

//获取个人用户信息
const fetchUserInfo = ()=>{
    return async (dispatch)=>{
        const res = await getUserInfoAPI()
        dispatch(setUserInfo(res.data))
    }
}

const {setToken,setUserInfo,clearUserInfo} = user.actions
const userReducer = user.reducer
export {fetchToken,fetchUserInfo,clearUserInfo}
export default userReducer